package yunjiao.javatutorials.guava.base.pairwise;

import com.google.common.base.Equivalence;

import java.util.Arrays;
import java.util.List;

/**
 * 处理 null 值
 *
 * @author yangyunjiao
 */
public class NullHandlingExample {
    public static void main(String[] args) {
        Equivalence<String> safeEquivalence = new Equivalence<String>() {
            @Override
            protected boolean doEquivalent(String a, String b) {
                // 处理 null 值
                if (a == b) return true;
                if (a == null || b == null) return false;
                return a.trim().equals(b.trim());
            }

            @Override
            protected int doHash(String s) {
                return s != null ? s.trim().hashCode() : 0;
            }
        };

        Equivalence<Iterable<String>> pairwiseSafe = safeEquivalence.pairwise();

        List<String> listWithNulls = Arrays.asList("hello", null, "world");
        List<String> listWithSpaces = Arrays.asList("hello", "  ", "world");

        System.out.println("包含null和包含空格的列表等价: " +
                pairwiseSafe.equivalent(listWithNulls, listWithSpaces)); // false
    }
}
